﻿using System.Collections.Generic;
using System.Configuration;
using System.Net;
using System;
using System.Linq;
using System.Text;

namespace Klinkby
{
    static class Replacer
    {
        readonly static Uri sourceUrl = new Uri(
            ConfigurationManager.AppSettings["sourceUrl"],
            UriKind.Absolute);
        readonly static string targetUrl = ConfigurationManager.AppSettings["targetUrl"];
        readonly static IEnumerable<KeyValuePair<string, string>> replacements 
            = new Queue<KeyValuePair<string,string>>(CreateReplacements());

        public static string ConvertText(HttpWebResponse response)
        {
            return replacements.Aggregate(
                new StringBuilder(response.GetContentString()), 
                (t, r) => t.Replace(r.Key, r.Value)
                ).ToString();
        }

        static IEnumerable<KeyValuePair<string, string>> CreateReplacements()
        {
            string sourceContent;
            for (
                int i = 1;
                (sourceContent = ConfigurationManager.AppSettings["sourceContent" + i.ToString()]) != null;
                i++)
                yield return new KeyValuePair<string, string>(
                    sourceContent,
                    ConfigurationManager.AppSettings["targetContent" + i.ToString()]
                    );
            yield return new KeyValuePair<string, string>(sourceUrl.OriginalString, targetUrl);
            yield return new KeyValuePair<string, string>(targetUrl + "/", targetUrl);
        }

        //static IEnumerable<KeyValuePair<string, string>> CreateReplacements()
        //{
        //    var q = new Queue<KeyValuePair<string, string>>();
            
        //    string sourceContent;
        //    for
        //        int i = 1;
        //        (sourceContent = ConfigurationManager.AppSettings["sourceContent" + i.ToString()]) != null;
        //        i++)
        //        q.Enqueue(new KeyValuePair<string, string>(
        //            sourceContent,
        //            ConfigurationManager.AppSettings["targetContent" + i.ToString()]
        //            ));
        //    return q;
        //}
    }
}